/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.dynamicform.core.statemachine;

import com.inspur.edp.lcm.metadata.api.IMetadataContent;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataHeader;
import com.inspur.edp.web.common.metadata.MetadataUtility;
import com.inspur.edp.web.common.utility.RandomUtility;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.dynamicform.core.api.entity.DynamicCreateFormMetadataParameter;
import com.inspur.edp.web.dynamicform.core.api.entity.FormMetadataInfo;
import com.inspur.edp.web.formmetadata.metadata.formdom.FormDOM;
import com.inspur.edp.web.statemachine.serializer.StateMachineTransferSerializer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 状态机元数据构造
 *
 * @author guozhiqi
 */
public class StateMachineMetadataGenerator {
    /**
     * 构造并保存状态机元数据
     *
     * @param parameter
     * @param formMetadataRelativePath
     * @param metadataInfoItem
     * @param formListMetadata
     * @param formDOM
     */
    public static void saveStateMachineAndRefreshForm(DynamicCreateFormMetadataParameter parameter, String formMetadataRelativePath, FormMetadataInfo metadataInfoItem, GspMetadata formListMetadata, FormDOM formDOM) {
        GspMetadata smMetadata = new GspMetadata();
        MetadataHeader smMetadataHeader = new MetadataHeader();
        smMetadataHeader.setName(metadataInfoItem.getName());
        smMetadataHeader.setCode(metadataInfoItem.getCode());
        smMetadataHeader.setFileName(metadataInfoItem.getCode() + "_frm.sm");
        smMetadataHeader.setId(RandomUtility.newGuid());
        smMetadataHeader.setNameSpace(parameter.getProjectNameSpace());
        smMetadataHeader.setBizobjectID(parameter.getBizobjectID());
        smMetadataHeader.setType("StateMachine");
        smMetadata.setHeader(smMetadataHeader);
        smMetadata.setRelativePath(formMetadataRelativePath);
        Optional<String> strStateMachineContent = getStateMachineContent(metadataInfoItem.getTemplateInfo().getTemplateId());
        // 保存对应的状态机元数据
        strStateMachineContent.ifPresent(smContent -> {
            StateMachineTransferSerializer serializer = new StateMachineTransferSerializer();
            IMetadataContent smMetadataContent = serializer.deserialize(smContent);
            smMetadata.setContent(smMetadataContent);
            // 保存状态机元数据
            MetadataUtility.getInstance().saveMetadataWithDesign(smMetadata);

            ArrayList<HashMap<String, Object>> stateMachineList = new ArrayList<>();
            HashMap<String, Object> stateMachineMap = new HashMap<>();
            stateMachineMap.put("id", formListMetadata.getHeader().getCode() + "_state_machine");
            stateMachineMap.put("name", formListMetadata.getHeader().getName() + "状态机");
            stateMachineMap.put("uri", smMetadata.getHeader().getId());
            stateMachineList.add(stateMachineMap);
            formDOM.getModule().setStateMachines(stateMachineList);

            // 更新对应的viewModel节点的状态机参数定义
            formDOM.getModule().getviewmodels().forEach(viewModelItem -> {
                // 仅在模板定义的位置 如果包含stateMachine 定义 那么更新该值为当前的状态机
                viewModelItem.computeIfPresent("stateMachine", (key, value) -> stateMachineMap.get("id"));
            });


        });
    }

    private static Optional<String> getStateMachineContent(String templateId) {
        if (StringUtility.isNullOrEmpty(templateId)) {
            return Optional.empty();
        }
        String strStateMachineContent = "";
        switch (templateId) {
            case "newListForm":
                strStateMachineContent = ListStateMachine.getContent();
                break;
            case "newCardForm":
            default:
                strStateMachineContent = CardStateMachine.getContent();
                break;
        }
        return Optional.ofNullable(strStateMachineContent);
    }

}
